package com.fone.player.activity.personal;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.fone.player.ApplicationManage;
import com.fone.player.R;
import com.fone.player.activity.BaseActivity;
import com.fone.player.billing.bean.ChargeRecordBean;
import com.fone.player.billing.bean.ChargeRecordListBean;
import com.fone.player.billing.util.common.PayEngine;
import com.fone.player.client.Callback;
import com.fone.player.client.Error;
import com.fone.player.client.RecordListRst;
import com.fone.player.client.Request;
import com.fone.player.util.FoneUtil;
import com.fone.player.util.L;
import com.fone.player.widget.xlistview.XListView;
import com.fone.player.widget.xlistview.XListView.IXListViewListener;


public class RecordActivity extends BaseActivity implements IXListViewListener {
	
	private static String TAG = "RecordActivity";
	
	public static String RECORDTYPE = "recordtype";
	
	public static final int CONSUME_RECORD = 1;//消费记录
	public static final int CHARGE_RECORD = 2;//充值记录
	
	private Button title_left_bt,title_right_bt;
	private TextView left_title_tv,un_record_tip;
	private XListView record_lv;
	private RecordListRst rst;
	private MyRecordAdapter mRecordAdapter;
	private LinearLayout waitting_ll; 
	private RelativeLayout un_record_rl;
	
	private ArrayList<ChargeRecordBean> chargeRecordsList;
	
	private String nextPageChargeUrl;
	
	private int type; // 2充值记录/1消费记录
	
	private Handler mHandler;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.personal_record_view);
		Intent intent = getIntent();
		type = intent.getIntExtra(RECORDTYPE, 1);
		L.v(TAG, "onCreate","recordtype : " + type);
		initHander();
		initView();
		initData();
	}
	
	@SuppressLint("HandlerLeak")
	private void initHander(){
		mHandler = new Handler(){

			@Override
			public void handleMessage(Message msg) {
				
				L.v(TAG, "handleMessage","handleMessage start");
				switch (msg.what) {
				case CHARGE_RECORD://充值记录
					if(msg.obj==null){
						L.v(TAG, "handleMessage","CHARGE_RECORD  msg.obj==null :" + true); 
						//超时重试
						FoneUtil.showToast(mContext, "数据查询失败,请重试");
						waitting_ll.setVisibility(View.GONE);
						return;
					}else{
						ChargeRecordListBean userChargeList = (ChargeRecordListBean)msg.obj;
						L.v(TAG, "handleMessage","CHARGE_RECORD  userChargeList.getRecords() :" + userChargeList.getRecords()); 
						if(userChargeList.getRecords()!=null && userChargeList.getRecords().size()>0){
							if(TextUtils.isEmpty(userChargeList.getNurl())){
								record_lv.setPullLoadEnable(false);
								record_lv.setEnableDragLoadMore(false);
							}else{
								nextPageChargeUrl = userChargeList.getNurl();
								record_lv.setPullLoadEnable(true);
								record_lv.setEnableDragLoadMore(true);
							}
							
							if(chargeRecordsList==null){
								chargeRecordsList = userChargeList.getRecords();
							}else{
								chargeRecordsList.addAll(chargeRecordsList);
							}
							//TODO 刷新数据
							mRecordAdapter.notifyDataSetChanged();
						}else{
							//TODO无充值记录 
							record_lv.setPullLoadEnable(false);
							record_lv.setEnableDragLoadMore(false);
							un_record_tip.setText("还没有充值记录");
							un_record_rl.setVisibility(View.VISIBLE);
						}
					}
					waitting_ll.setVisibility(View.GONE);
					break;
				case CONSUME_RECORD://消费记录
					L.v(TAG, "handleMessage","CONSUME_RECORD  consumelist :" + rst.consumelist); 
					if(rst.consumelist!=null 
							&& rst.consumelist.consumes!=null 
								&& rst.consumelist.consumes.size()>0){
						mRecordAdapter.notifyDataSetChanged();
					}else{
						//TODO 没有消费记录
						un_record_tip.setText("还没有消费记录");
						un_record_rl.setVisibility(View.VISIBLE);
					}
					waitting_ll.setVisibility(View.GONE);
					break;
				default:
					break;
				}
			}
		};
	}
	
	private void initView(){
		title_left_bt = (Button) findViewById(R.id.common_title_left_bt);
		title_right_bt = (Button) findViewById(R.id.common_title_right_bt);
		left_title_tv = (TextView) findViewById(R.id.common_left_title_tv);
		record_lv = (XListView) findViewById(R.id.record_lv);
		waitting_ll = (LinearLayout) findViewById(R.id.record_waitting_ll);
		un_record_rl = (RelativeLayout) findViewById(R.id.un_record_rl);
		un_record_tip = (TextView) findViewById(R.id.un_record_tip);
		title_right_bt.setVisibility(View.GONE);
		
		record_lv.setPullRefreshEnable(false);
		record_lv.setPullLoadEnable(false);
		record_lv.setEnableDragLoadMore(false);
		record_lv.setXListViewListener(this);
		
		mRecordAdapter = new MyRecordAdapter(type);
		record_lv.setAdapter(mRecordAdapter);
		
		if(type == CHARGE_RECORD){
			left_title_tv.setText("充值记录");
		}else if(type == CONSUME_RECORD){
			left_title_tv.setText("消费记录");
		}
		left_title_tv.setVisibility(View.VISIBLE);
		title_left_bt.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				finish();
			}
		});
	}
	
	private void initData(){
		// 请求数据
		if(FoneUtil.isNetOkWithToast(mContext)){
			waitting_ll.setVisibility(View.VISIBLE);
			if(type == 2){
				requestChargeData(PayEngine.getUserChargHistUrl(ApplicationManage.getGlobalContext()));//请求充值记录
			}else{
				Request.getInstance().recordList(type, new RecordListRstCallBack(type));
			}
		}
	}
	
	/**
	 * 请求充值记录数据
	 */
	private void requestChargeData(final String chargeRecordUrl){
		
		L.v(TAG, "requestChargeData","chargeRecordUrl : " + chargeRecordUrl);
		record_lv.setPullLoadEnable(false);
		record_lv.setEnableDragLoadMore(false);
		
		if(TextUtils.isEmpty(chargeRecordUrl)){
			return;
		}
		new Thread(){
			public void run() {
				ChargeRecordListBean ChargeList = PayEngine.getUserChargeList(chargeRecordUrl,null,PayEngine.GET);
				mHandler.obtainMessage(CHARGE_RECORD, ChargeList).sendToTarget();
			};
		}.start();
	}
	
	private class MyRecordAdapter extends BaseAdapter{

		private int type;
		
		public MyRecordAdapter(int type){
			this.type = type;
		}
		
		@Override
		public int getCount() {
			if(type==CHARGE_RECORD && chargeRecordsList!=null){
				return chargeRecordsList.size();
			}else if(type==CONSUME_RECORD && rst!=null && rst.consumelist!=null && rst.consumelist.consumes!=null){
				return rst.consumelist.consumes.size();
			}
			return 0;
		}

		@Override
		public Object getItem(int position) {
			return null;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			Holder mHolder;
			if(convertView==null){
				
				mHolder = new Holder();
				convertView = View.inflate(mContext, R.layout.record_item, null);
				if(type == CHARGE_RECORD){//充值记录
					initChargeView(mHolder, convertView);
				}else if(type == CONSUME_RECORD){//消费记录
					initConsumeView(mHolder, convertView);
				}
				
			}else{
				mHolder = (Holder) convertView.getTag();
			}
			
			if(type == CHARGE_RECORD){
				//充值
				mHolder.record_charge_time_tv.setText(chargeRecordsList.get(position).getTime());
				mHolder.record_charge_channel_tv.setText(chargeRecordsList.get(position).getChannel());
				mHolder.record_charge_count_tv.setText(chargeRecordsList.get(position).getRmb()+"元");
			}else if(type == CONSUME_RECORD){
				//消费
				mHolder.record_consume_time_tv.setText(formatTime(rst.consumelist.consumes.get(position).time));
				
				switch (rst.consumelist.consumes.get(position).type) {
				case 1: // 礼物
					mHolder.record_consume_type_tv.setText("购买礼物");
					break;
				case 2: // 开通VIP
					mHolder.record_consume_type_tv.setText("购买VIP");
					break;
				default:
					break;
				}
				mHolder.record_consume_count_tv.setText(rst.consumelist.consumes.get(position).vb+"v币");
			}
			
			convertView.setTag(mHolder);
			
			return convertView;
		}
		
		private String formatTime(long time){
			if(time==0){
				return "";
			}
           return new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(new Date(time));
		}
		
		/**
		 * 初始化充值View
		 * @param mHolder
		 * @param convertView
		 */
		private void initChargeView(Holder mHolder,View convertView){
			mHolder.record_charge_ll = (LinearLayout) convertView.findViewById(R.id.record_charge_ll);
			mHolder.record_charge_time_tv = (TextView) convertView.findViewById(R.id.record_charge_time_tv);
			mHolder.record_charge_channel_tv = (TextView) convertView.findViewById(R.id.record_charge_channel_tv);
			mHolder.record_charge_count_tv = (TextView) convertView.findViewById(R.id.record_charge_count_tv);
			mHolder.record_charge_ll.setVisibility(View.VISIBLE);
		}
		
		/**
		 * 初始化消费View
		 * @param mHolder
		 * @param convertView
		 */
		private void initConsumeView(Holder mHolder,View convertView){
			mHolder.record_consume_ll = (LinearLayout) convertView.findViewById(R.id.record_consume_ll);
			mHolder.record_consume_time_tv = (TextView) convertView.findViewById(R.id.record_consume_time_tv);
			mHolder.record_consume_type_tv = (TextView) convertView.findViewById(R.id.record_consume_type_tv);
			mHolder.record_consume_count_tv = (TextView) convertView.findViewById(R.id.record_consume_count_tv);
			mHolder.record_consume_ll.setVisibility(View.VISIBLE);
		}
		
		private class Holder{
			public LinearLayout record_charge_ll,record_consume_ll;
			public TextView record_charge_time_tv,record_consume_time_tv;
			public TextView record_charge_channel_tv,record_consume_type_tv;
			public TextView record_charge_count_tv,record_consume_count_tv;
		}
		
	}
	
	private class RecordListRstCallBack implements Callback<RecordListRst>{

		private int type;
		
		public RecordListRstCallBack(int type){
			this.type = type;
		}
		
		@Override
		public void onSuccess(RecordListRst t) {
			L.v(TAG, "RecordListRstCallBack onSuccess", t.toString());
			if(t.result!=0){
				FoneUtil.showToast(mContext, "数据获取失败，请重试");
				waitting_ll.setVisibility(View.GONE);
				return;
			}
			rst = t;
			Message msg = mHandler.obtainMessage();
			msg.what = this.type;
			mHandler.sendMessage(msg);
		}

		@Override
		public void onFailure(Error error) {
			waitting_ll.setVisibility(View.GONE);
			L.v(TAG,
					"RecordListRstCallBack onFailure",
					"isNetworkError : " + error.isNetworkError() + " status : "
							+ error.getStatus() + " reason : "
							+ error.getReason());
			
			if(error.isNetworkError()){
				FoneUtil.showToast(mContext, "网络超时,请稍后重试");
				return ;
			}
			FoneUtil.showToast(mContext, "数据查询失败,请重试");
		}
	}

	@Override
	public void onRefresh() {}

	@Override
	public void onLoadMore() {
		L.v(TAG, "onLoadMore","type : " + type);
		if(FoneUtil.isNetOkWithToast(mContext)){
			if(type == 2){
				requestChargeData(nextPageChargeUrl);
			}
		}
	}
	
}
